import Vue from 'vue'
import http from '../utils/http'
import constant from '../utils/constant'
// import myDatepicker from 'vue-datepicker/vue-datepicker-es6.vue'
import VueFlatPickr from 'vue-flatpickr-component'
import 'flatpickr/dist/flatpickr.css'
import store from '../vuex/mobile'
import Calendar from 'vue2-slot-calendar'
import {formatDate} from './../utils/date.js'

let today = new Date()
today.setDate(today.getDate() + 2)
export default {
  name: 'renting',
  data() {
    return {
      disabled: 'disabled',
      supplierDrop: true,
      categoriesDrop: true,
      typeDrop: true,
      suppliersData: undefined,    // 请求得到的供应商数据
      suppliersArray: undefined,   //根据国家获取供应商
      suppliers: undefined,        // selete 供应商 需要的数据
      countryShow: false,
      currentLetter: '',
      countriesOptions: '',
      currentHotLetter: '',
      driverAge: [],
      ageSelected: '25岁',
      selectedCountry: 'US,CA',
      selectedCountryId: 93,
      selectedCountryName: '北美',
      suppliers: [{
        chinese_name: "Enterprise",
        code: "Enterprise",
        id: 1
      },{
        chinese_name: "爱路美",
        code: "Alamo",
        id: 2
      },{
        chinese_name: "National",
        code: "National",
        id: 3
      }],
      selectedsupplier: {
        chinese_name: "爱路美",
        code: "Alamo",
        id: 2
      },
      suppliersId: 2,
      suppliersCode: 'Alamo',
      currentCountryIndex: '',
      currentCountryId: '',
      currentShowModal: '',
      hotLocations: '',
      currentCityIndex: '',
      selectedCityName: '',
      selectedCityId: undefined,
      currentCityId: '',
      returnCityName: undefined,
      returnCityCode: undefined,
      returnCityId: undefined,
      returnCurrentCityId: undefined,
      returnCurrentCityIndex: undefined,
      returnCurrentSearchCityIndex: undefined,
      hotCityShow: false,
      currentSearchCityIndex: '',
      selectCategories: undefined,
      typeOptions: undefined,
      selectedType: '',
      setCategories: undefined,
      searchCityVal: '',
      searchCityData: '',
      tooltipEle: '',
      tooltipMsg: '',
      senderName: '',
      senderAddress: '',
      senderDate: '',
      senderMobile: '',
      senderMessage: '',
      emailUrl: '',
      slide: 0,
      sliding: null,
      showT: 1,
      pickupDate: formatDate(new Date(), 'yyyy-MM-dd'),
      returnDate: formatDate(today, 'yyyy-MM-dd'),
      // pickupDateText: undefined,
      // pickupTimeText: undefined,
      // returnDateText: undefined,
      // returnTimeText: undefined,
      // config: {
      //   minDate: new Date().fp_incr(-1),
      //   enableTime: true,
      //   time_24hr: true,
      //   minuteIncrement: 30
      // },
      disabled: true,
      format: "yyyy-MM-dd",
      clear: false,
      placeholder: "Start Date",
      lang: 'zhCN',
      dateTime: ['00:00', '00:30', '01:00', '01:30', '02:00', '02:30', '03:00', '03:30', '04:00', '04:30', '05:00', '05:30', '06:00', '06:30', '07:00', '07:30', 
      '08:00', '08:30', '09:00', '09:30', '10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00', '15:30', '16:00', '16:30',
      '17:00', '17:30', '18:00', '18:30', '19:00', '19:30', '20:00', '20:30', '21:00', '21:30', '22:00', '22:30', '23:00', '23:30'],
      pickupTime: '12:00',
      returnTime: '12:00',
      minDate: formatDate(new Date().fp_incr(-1), 'yyyy-MM-dd')
    }
  },
  components: {
    // 'date-picker': myDatepicker,
    'flat-pickr': VueFlatPickr,
    calendar: Calendar
  },
  mounted() {
    let that = this
    this.requestCountry()
    this.requestSuppliers()
    this.requestSets()
    this.requestCategories()
    this.initDriverAge()

    this.$nextTick(function () {
      this.$root.$on('bv::modal::hide', (bvEvent, modalId) => {
        // 根据国家选择相应套餐
        if (modalId === 'countryModal' && that.suppliersArray && that.suppliersArray != undefined) {
          let suppliersOption = that.suppliersArray.split(',')
          let suppliers = []
          for (let key in that.suppliersData) {
            for (let k in suppliersOption) {
              if (key === suppliersOption[k]) {
                suppliers.push(that.suppliersData[key])
              }
            }
          }
          that.$set(this.$data, 'suppliers', suppliers)
          }
      })

      this.$root.$on('bv::modal::show', (bvEvent, modalId) => {
        
        if(modalId === 'city-modal') {
          this.$set(this.$data, 'searchCityVal', "")
          this.$set(this.$data, 'hotCityShow', false)
          this.searchCityData = ''
        }
      })
      // this.$forceUpdate()
    })
  },
  methods: {
    onDayClick1 (date, str) {
      this.date1 = str
    },
    initDriverAge() {
      let ageArr = [];
      for(let i = 18; i<= 30; i++) {
        if(i == 30) {
          ageArr.push({code: i, value: i+"或" + i +'岁以上'})
        } else {
          ageArr.push({code: i, value:i+"岁"})
        }
      }

      this.driverAge = ageArr
    },
    requestCountry() {
      const that = this
      http.get(constant.counties, null, function(response) {
        that.$set(that.$data, 'countriesOptions', response.countries)
      }, function(response) {
        console.log(response)
      })
    },

    requestSuppliers() {
      const that = this
      http.get(constant.suppliers, null, function(response) {
        that.$set(that.$data, 'suppliersData', response.suppliers)
      }, function(response) {
        console.log(response)
      })
    },

    requestSets() {
      const that = this
      http.get(constant.carsSets, null, function(response) {
        that.carsSets = response.sets
      }, function(response) {
        console.log(response)
      })
    },

    requestCategories() {
      const that = this
      http.get(constant.carsCategories, null, function(response) {
        that.carsCategories =  response.setCategories
      }, function(response) {
        console.log(response)
      })
    },

    resetModal() {
      this.$set(this.$data, 'selectedCountry', '')
      this.$set(this.$data, 'selectedCountryId', '')
      this.$set(this.$data, 'selectedCountryName', '')
      this.$set(this.$data, 'currentCountryId', '')
      this.$set(this.$data, 'currentCountryIndex', '')
    },

    bindSelectCountry(index, key, ev) {
      this.$nextTick(function () {
        this.$set(this.$data, 'selectedCountry', ev.currentTarget.getAttribute('data-country-code'))
        this.$set(this.$data, 'selectedCountryId', ev.currentTarget.getAttribute('data-country-id'))
        this.$set(this.$data, 'selectedCountryName', ev.currentTarget.getAttribute('data-country-name'))
        this.$set(this.$data, 'currentCountryIndex', index)
        this.$set(this.$data, 'currentCountryId', key)
        this.$set(this.$data, 'suppliersArray', ev.currentTarget.getAttribute('data-suppliers'))
      })
    },

    selectCitiesLetter(index) {
      console.log(index)
      this.$set(this.$data, 'currentLetter', index)
    },

    selectHotCitiesLetter(index) {
      this.$set(this.$data, 'currentHotLetter', index)
    },

    onSearchBrand(value) {
      let _this = this
      var values = this.selectedCountry
      if (values === '') {
        console.log('未选中国家')
        this.$root.$emit('bv::show::tooltip', 'countryEle')
        setTimeout(function() {
          _this.closeTooltip()
        }, 1500)
      } else {
        this.$set(this.$data, 'supplierDrop', false)
      }
    },
    generateBrand() {
      console.log(this.selectedsupplier)
      this.$set(this.$data, 'suppliersCode', this.selectedsupplier.code)
      this.$set(this.$data, 'suppliersId', this.selectedsupplier.id)
    },

    onSearchType(value) {
      let _this = this
      let countryValues = this.selectedCountry
      let supplierValues = this.suppliersCode
      let pickupSiteValues = this.selectedPickupSite
      let returnSiteValues = this.selectedReturnSite
      if (countryValues === '') {
        this.$root.$emit('bv::show::tooltip', 'countryEle')
        setTimeout(function() {
          _this.closeTooltip()
        }, 1500)
        return
      } else if (supplierValues === '') {
        this.$root.$emit('bv::show::tooltip', 'brandEle')
        setTimeout(function() {
          _this.closeTooltip()
        }, 1500)
        return
      } else if (pickupSiteValues === '') {
        this.$root.$emit('bv::show::tooltip', 'pickupSiteEle')
        setTimeout(function() {
          _this.closeTooltip()
        }, 1500)
        return
      } else if (returnSiteValues === '') {
        this.$root.$emit('bv::show::tooltip', 'returnSiteEle')
        setTimeout(function() {
          _this.closeTooltip()
        }, 1500)
        return
      }
      
      this.generateData()
      this.$set(this.$data, 'typeDrop', false)
    },

    generateData() {
      // 根据 countryCode 和 suppliersId 获取付款方式
      let countryCode = this.selectedCityCode ? this.selectedCityCode.split(",") : this.selectedCountry.split(",")
      let suppliersId = this.suppliersId
      let carsCountrySets = []
      let payArr = []
      console.log(this.selectedCityCode)
      for(let i in countryCode) {
        carsCountrySets.push(this.carsSets[countryCode[i]][suppliersId])
      }
      
      for(let j in carsCountrySets) {
        for(let index in carsCountrySets[j]) {
          let paytype = carsCountrySets[j][index].pay_type
          var obj = {}

          if (paytype && paytype === 'ARRIVEPAY') {
            obj.payCode = 'ARRIVEPAY'
            obj.payName = '到付'
            payArr.push(obj)
          } else if(paytype && paytype != 'ARRIVEPAY') {
            obj.payCode = 'PREPAY'
            obj.payName = '预付'
            payArr.push(obj)
          }
        }
      }

      let newPyaArr= {};
  
      payArr = payArr.reduce(function(item, next) {
        newPyaArr[next.payCode] ? '' : newPyaArr[next.payCode] = true && item.push(next);
        return item
      }, [])

      this.$set(this.$data, 'typeOptions', payArr)
    },

    onSearchCategories(value) {
      let _this = this
      let countryValues = this.selectedCountry
      let supplierValues = this.suppliersId
      let pickupSiteValues = this.selectedCityCode
      let returnSiteValues = this.returnCityCode
      let typeValues = this.selectedType

      if (countryValues === '') {
        this.$root.$emit('bv::show::tooltip', 'countryEle')
        setTimeout(function() {
          _this.closeTooltip()
        }, 1500)
        return
      } else if (supplierValues === '') {
        this.$root.$emit('bv::show::tooltip', 'brandEle')
        setTimeout(function() {
          _this.closeTooltip()
        }, 1500)
        return
      } else if (pickupSiteValues === '') {
        this.$root.$emit('bv::show::tooltip', 'pickupSiteEle')
        setTimeout(function() {
          _this.closeTooltip()
        }, 1500)
        return
      } else if (returnSiteValues === '') {
        this.$root.$emit('bv::show::tooltip', 'returnSiteEle')
        setTimeout(function() {
          _this.closeTooltip()
        }, 1500)
        return
      } else if (typeValues === '') {
        this.$root.$emit('bv::show::tooltip', 'typeEle')
        setTimeout(function() {
          _this.closeTooltip()
        }, 1500)
        return
      }
      this.generateCategoriesData()
      this.$set(this.$data, 'categoriesDrop', false)
    },

    generateCategoriesData() {
      // 根据 countryCode 和 suppliersId payId 获取套餐
      let countryCode = this.selectedCityCode ? this.selectedCityCode.split(",") : this.selectedCountry.split(",")
      let suppliersId = this.suppliersId
      let carsCountrySets = []
      let categotyArr = []
      for(let i in countryCode) {
        carsCountrySets.push(this.carsSets[countryCode[i]][suppliersId])
      }

      for(let j in carsCountrySets) {
        for(let index in carsCountrySets[j]) {
          let pay_type = carsCountrySets[j][index].pay_type == 'ARRIVEPAY' ? 'ARRIVEPAY' : 'PREPAY'
          let categotyId = carsCountrySets[j][index].categoty
          if( pay_type === this.selectedType && categotyArr.indexOf(categotyId) == -1){
            categotyArr.push(categotyId);
          }
        }
      }

      let categoriesOpt = []
      for(let key of categotyArr) {
        categoriesOpt.push(this.carsCategories[key])
      }
           
      this.$set(this.$data, 'setCategories', categoriesOpt)
    },

    hotCitiesShow(key) {
      const that = this
      let countryValues = this.selectedCountry
      let supplierValues = this.suppliersCode
     
      if (countryValues === '') {
        this.$root.$emit('bv::show::tooltip', 'countryEle')
        setTimeout(function() {
          that.closeTooltip()
        }, 1500)
        return
      } else if (supplierValues === '') {
        this.$root.$emit('bv::show::tooltip', 'brandEle')
        setTimeout(function() {
          that.closeTooltip()
        }, 1500)
        return
      } else {
        that.requestHotCities(key);
        this.$refs['city-modal'].show()
      }
    },

    requestHotCities(value) {
      const that = this
      let parma = {
        'country': that.$data.selectedCountry,
        'brand': that.$data.suppliersCode
      }
      
      http.get(constant.hotLocation, parma, function(response) {
        that.$set(that.$data, 'hotLocations', response.locations)
        that.$set(that.$data, 'currentShowModal', value)
      }, function(result) {
        console.log(result)
      })
    },

    bindSelectCity(index, key, ev) {
      
      if (this.currentShowModal === 'pickup') {
        this.selectedCityName= ev.currentTarget.getAttribute('data-city-name')
        this.selectedCityCode= ev.currentTarget.getAttribute('data-city-code')
        this.selectedCityId= ev.currentTarget.getAttribute('data-city-id')
        this.currentCityIndex= index
        this.currentCityId= key
      } else if (this.currentShowModal === 'return') {
        this.returnCityName= ev.currentTarget.getAttribute('data-city-name')
        this.returnCityCode= ev.currentTarget.getAttribute('data-city-code')
        this.returnCityId= ev.currentTarget.getAttribute('data-city-id')
        this.returnCurrentCityIndex= index
        this.returnCurrentCityId= key
      }

      this.$refs['city-modal'].hide()
    },

    bindSearchCity(index, ev) {
      if (this.currentShowModal === 'pickup') {
          this.selectedCityName = ev.currentTarget.getAttribute('data-city-name')
          this.selectedCityCode = ev.currentTarget.getAttribute('data-city-code')
          this.selectedCityId = ev.currentTarget.getAttribute('data-city-id')
          this.currentSearchCityIndex = index
          
      } else if (this.currentShowModal === 'return') {
          this.returnCityName = ev.currentTarget.getAttribute('data-city-name')
          this.returnCityCode = ev.currentTarget.getAttribute('data-city-code')
          this.returnCityId = ev.currentTarget.getAttribute('data-city-id')
          this.returnCurrentSearchCityIndex = index
      }
      this.$refs['city-modal'].hide()
    },

    searchCity() {
      const that = this
      let country = this.selectedCountry
      let brand = this.suppliersCode
      let codeString = this.searchCityVal
      let parma = {
        'country': country,
        'brand': brand,
        'code': codeString
      }
      
      if(this.searchCityVal && this.searchCityVal.length >=2) {
        http.get(constant.searchLocation, parma, function(response) {
          if(response.locations && response.locations.length >= 1) {
            that.$set(that.$data, 'searchCityData', response.locations)
            that.hotCityShow = true 
          }
        })
      } else {
        console.log()
      }
    },

    doSomethingOnClose(value) {
      if(value == 'pickup') {
        this.$set(this.$data, `${value}DateText`, this.pickupDate.split(" ")[0])
        this.$set(this.$data, `${value}TimeText`, this.pickupDate.split(" ")[1])
      } else {
        this.$set(this.$data, `${value}DateText`, this.returnDate.split(" ")[0])
        this.$set(this.$data, `${value}TimeText`, this.returnDate.split(" ")[1])
      }
    },

    onSlideStart(slide) {
      this.sliding = true
    },
    onSlideEnd(slide) {
      this.sliding = false
    },

    showDescription(value) {
      this.$set(this.$data, 'showT', value)
    },

    leave() {
      this.$set(this.$data, 'showT', 1)
    },

    closeTooltip() {
      this.$root.$emit('bv::hide::tooltip')
    },

    goToResult() {
      let countryName = this.selectedCountryName
      let countryId = this.selectedCountryId
      let countryCode = this.selectedCountry
      let supplierId = this.selectedsupplier.id
      let pickupLocation = this.selectedCityId
      let returnLocation = this.returnCityId
      let pickupDate = this.pickupDate 
      let returnDate = this.returnDate
      let pickupTime = this.pickupTime
      let returnTime = this.returnTime
      let driveAge = this.ageSelected.toString().indexOf("岁") > 0 ? this.ageSelected.replace(/岁/g,'') : this.ageSelected;
      let type = this.selectedType
      let setCategoryId = this.selectCategories

      if(!countryId || !countryCode || !supplierId || !pickupLocation || !returnLocation || !pickupDate || !returnDate || !pickupTime || !returnTime || !driveAge || !type || !setCategoryId) {
        this.$message.error({
          message: '请完善表单',
          align: 'center'
        })
        return 
      }

      if(!this.$attrs.suppliersData) {
        store.dispatch('setSuppliersData', this.selectedsupplier)
      } else {
        this.selectedsupplier = this.$store.getters.getSuppliersData
      } 
      
      let locationArr = [this.selectedCityName, this.returnCityName]
      if(!this.$attrs.carLocation) {
        store.dispatch('setCarLocation', locationArr)
      } else {
        this.selectedCityName = this.$store.getters.getCarLocation[0]
        this.returnCityName = this.$store.getters.getCarLocation[1]
      } 

      this.$router.push({name: 'searchResult',
        query: {
          filter: true,
          countryName: countryName,
          countryId: countryId,
          countryCode: countryCode,
          supplierId: supplierId,
          pickupLocation: pickupLocation,
          returnLocation: returnLocation,
          pickupDate: pickupDate + ' ' + pickupTime, 
          returnDate: returnDate + ' ' + returnTime,
          driveAge: driveAge,
          type: type,
          setCategoryId: setCategoryId
        }
      })
    },

    sendMail() {
      let emailBody = `姓名: ${this.senderName}\n目的地: ${this.senderAddress}\n天数: ${this.senderDate}\n联系方式: ${this.senderMobile}\n备注: ${this.senderMessage}`
      this.$set(this.$data, 'emailUrl', 'mailto:shainfo@chinaholidaytours.com?body=' + emailBody)
    },

    processResult(response, success, failure) {
      let result = typeof response === 'object' ? response : this.parseJSON(response)
      if (result && parseInt(result.data.code) === 0) {
        success && success(result)
      } else if (failure) {
        failure(result)
      } else {
        console.warn('No function found handling result: ', result)
      }
    }
  },
  watch: {
    selectedCountryName(curVal, oldVal) {
      this.selectedsupplier = ''
      this.selectedCityName = ''
      this.returnCityName = ''
      this.selectedType = null
      this.selectCategories = null
      this.$refs.typeSelect.clearSelection();    
      this.$refs.categorySelect.clearSelection();  
    },

    selectedCityName() {
      if(this.returnCityCode === undefined) {
        this.$set(this.$data, 'returnCityName', this.selectedCityName)
        this.$set(this.$data, 'returnCityCode', this.selectedCityCode)
        this.$set(this.$data, 'returnCityId', this.selectedCityId)
        this.$set(this.$data, 'returnCurrentCityIndex', this.currentCityIndex)
        this.$set(this.$data, 'returnCurrentCityId', this.currentCityId)
      }
    },

    searchCityVal(curVal) {
      if(curVal.length >=2 ) {
        this.searchCity()
      } else {
        this.searchCityData = ''
      }
    },

    pickupDate(curVal) {
      let twoDays = new Date(curVal)
      twoDays.setDate(twoDays.getDate() + 2)
      if(this.returnDate < curVal) {
        this.returnDate = formatDate(twoDays, 'yyyy-MM-dd')
      }
    }
  }
}